package com.xz.xzutils.module.xzmybatislog;

import com.intellij.execution.filters.Filter;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * <p>
 * 用于过滤控制台输出，用于收集mybatis日志
 * </p>
 *
 * @author DONG.WANG17@HAND-CHINA.COM
 * @since 2025-01-14 19:59
 */
public class XzMyBatisLogConsoleFilter implements Filter {
    private static final Logger LOGGER = Logger.getInstance(XzMyBatisLogConsoleFilter.class);
    private static XzMyBatisLogConsoleFilter instance;
    private final Project project;

    private XzMyBatisLogConsoleFilter(Project project) {
        this.project = project;
    }

    public static XzMyBatisLogConsoleFilter getInstance(Project project) {
        if (null == instance) {
            instance = new XzMyBatisLogConsoleFilter(project);
        }
        return instance;
    }

    @Override
    public @Nullable Result applyFilter(@NotNull String line, int entireLength) {
        LOGGER.info("applyFilter:" + line);
        if (StringUtils.isBlank(line) || (!line.contains(XzMybatisLogManager.PARAM_PREFIX) && !line.contains(XzMybatisLogManager.SQL_PREFIX))) {
            return null;
        }
        XzMybatisLogManager manager = project.getUserData(XzMybatisLogManager.KEY);
        if (null == manager) return null;
        manager.addLine(line);
        return null;
    }
}
